mod args;
mod logger;

use anyhow::Result;
use clap::Parser;
use std::sync::Arc;
use tracing::{error, info};

use rmcp::{ServiceExt, transport::stdio};
use rmcp_db::db::DatabaseManager;
use rmcp_db::db_handler::RbdcDatabaseHandler;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    let args = args::Args::parse();

    logger::init(args.log_level);

    info!("====================[RMCP SQLEXEC STDIO]====================");

    // Create database manager
    let db_manager = DatabaseManager::new(&args.database_url).map_err(|e| {
        error!("[stdio] Failed to create database manager: {}", e);
        anyhow::Error::msg(e.to_string())
    })?;

    // Configure connection pool
    db_manager
        .configure_pool(args.max_connections, args.timeout)
        .await;

    // Test database connection
    db_manager
        .test_connection()
        .await
        .map_err(|e| anyhow::Error::msg(format!("[stdio] Database connection test failed: {e}")))?;

    info!("[stdio] Database connection test successful");

    // Create database handler
    let handler = RbdcDatabaseHandler::new(Arc::new(db_manager));

    info!("[stdio] Starting RMCP SQLEXEC Server...");

    // Start server
    let service = handler.serve(stdio()).await.inspect_err(|e| {
        error!("[stdio] Server startup failed: {:?}", e);
    })?;

    info!("[stdio] Starting Server Completed");

    service.waiting().await?;

    info!("[stdio] Server end");

    Ok(())
}
